package com.honghu.villagepost.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ObjectUtils
import com.google.gson.Gson
import com.honghu.villagepost.R
import com.honghu.villagepost.adapter.GoodsImageAdapter
import com.honghu.villagepost.adapter.ImageAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseActivity
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.constant.Constants
import com.honghu.villagepost.dao.manager.DbManager
import com.honghu.villagepost.entity.BannerEntity
import com.honghu.villagepost.entity.Goods
import com.honghu.villagepost.entity.event.CatRefreshEvent
import com.honghu.villagepost.widget.ProductSkuDialog
import com.jaeger.library.StatusBarUtil
import com.lzy.okgo.model.Response
import com.wuhenzhizao.sku.bean.Sku
import com.wuhenzhizao.sku.bean.SkuAttribute
import com.wuhenzhizao.titlebar.utils.AppUtils
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.activity_goods_details.*
import org.greenrobot.eventbus.EventBus
import java.util.*
import kotlin.collections.ArrayList


/**
 * @author: mqwang
 * @create: 2/7/21 3:39 PM
 * @Description:
 */
class GoodsDetailsActivity : BaseActivity(), LifecycleOwner {

    private var productSkuDialog: ProductSkuDialog? = null
    private var selectSku: Sku? = null
    private var goodsId: Int = 0
    private var selectQuantity: Int = 0
    private lateinit var goods: Goods

    private val bannerEntities: MutableList<BannerEntity> = ArrayList()

    private val goodsImageAdapter: GoodsImageAdapter by lazy {
        GoodsImageAdapter()
    }

    private val imageAdapter: ImageAdapter by lazy {
        ImageAdapter(bannerEntities)
    }

    companion object {
        fun self(context: Context?, goodsId: Int) {
            val intent = Intent(context, GoodsDetailsActivity::class.java)
            intent.putExtra(Constants.GOODS_ID, goodsId)
            context!!.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_goods_details
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {
        setMainTitle("详情")

        goodsId = intent.getIntExtra(Constants.GOODS_ID, 0)


        recycler_view.adapter = goodsImageAdapter

        banner.adapter = imageAdapter
        banner.addBannerLifecycleObserver(this)
        banner.indicator = CircleIndicator(mContext)

        tv_cart.setOnClickListener {
            if (goods != null) {
                showSkuDialog(false)
            }
        }

        tv_settle.setOnClickListener {
            if (isLogin(true)) {

                if (selectSku == null) {
                    showSkuDialog(true)
                    return@setOnClickListener
                }

                val settleItemList: MutableList<MutableMap<String, Any>> = ArrayList()

                val map: MutableMap<String, Any> = HashMap()

                map.put("quantity", selectQuantity)
                map.put("skuId", selectSku!!.id)

                settleItemList.add(map)

                OrderDetailsActivity.self(this, goods.shopId, Gson().toJson(settleItemList))
//                SubmitOrderActivity.self(this, goods.shopId, settleItemList)
            }
        }

        ApiService.goods_id(this, goodsId, object : DialogCallback<LzyResponse<Goods>>() {

            override fun onSuccess(response: Response<LzyResponse<Goods>>?) {
                goods = response!!.body().data
                if (goods != null) {
                    tv_name.setText(goods.catName)
                    tv_addr.setText(goods!!.catName)

                    tv_price.setText(getString(R.string.price_format, goods.price))

                    if (!ObjectUtils.isEmpty(goods.goodsPicList)) {
                        goodsImageAdapter.setNewData(goods.goodsPicList)
                    }


                    bannerEntities.add(BannerEntity(goods.majorPic))

                    imageAdapter.notifyDataSetChanged()

                    if (!ObjectUtils.isEmpty(goods.goodsSkuList)) {
                        var skuList: MutableList<Sku> = ArrayList()

                        for (index in 0..goods.goodsSkuList.size - 1) {
                            var goodsSku = goods.goodsSkuList.get(index)
                            var sku = Sku()
                            sku.id = goodsSku.id.toString()
                            sku.stockQuantity = goodsSku.stock
                            sku.originPrice = goodsSku.price!!
                            sku.sellingPrice = goodsSku.price!!

                            var skuAttributes: MutableList<SkuAttribute> = ArrayList()

                            var skuAttribute1 = SkuAttribute()
                            skuAttribute1.key = "颜色"
                            skuAttribute1.value = goodsSku.color
                            var skuAttribute2 = SkuAttribute()

                            skuAttribute2.key = "尺码"
                            skuAttribute2.value = goodsSku.size

                            skuAttributes.add(skuAttribute1)
                            skuAttributes.add(skuAttribute2)

                            sku.attributes = skuAttributes

                            skuList.add(sku)

                        }

                        goods.skuList = skuList
                    }

                }
            }
        })
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        AppUtils.transparencyBar(window)
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorWhite), 0);
        StatusBarUtil.setLightMode(this)
//        AppUtils.supportStatusBarLightMode(window)
    }

    private fun showSkuDialog(buySoon: Boolean) {
        if (isLogin(true)){
            //如果是登陆状态，才可加入购物车
            if (productSkuDialog == null) {
                productSkuDialog = ProductSkuDialog()
                productSkuDialog!!.setData(goods, object : ProductSkuDialog.Callback {
                    override fun onAdded(sku: Sku?, quantity: Int) {
                        if (selectSku != null && selectSku?.id.equals(sku?.id)) {
                            selectQuantity = selectQuantity + quantity
                        } else {
                            selectQuantity = quantity
                        }
                        selectSku = sku;
                        tv_total_price.setText(getString(R.string.price_format, selectQuantity * sku!!.sellingPrice))
                        tv_buy_num.setText(getString(R.string.buy_num_format, selectQuantity))
                        if (buySoon) {
                            tv_settle.performClick()
                        }

                        //添加商品到购物车数据库
                        DbManager.getInstance().addCat(goods, selectQuantity, selectSku)
                        EventBus.getDefault().post(CatRefreshEvent())
                    }
                })
            }
            productSkuDialog!!.show(supportFragmentManager, "ProductSkuDialog")
        }
    }

    //方法一：自己控制banner的生命周期

    //方法一：自己控制banner的生命周期
    override fun onStart() {
        super.onStart()
        //开始轮播
        banner.start()
    }

    override fun onStop() {
        super.onStop()
        //停止轮播
        banner.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        //销毁
        banner.destroy()
    }

}